<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="table-view">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" class="grid grid-cols-3 gap-x-3" v-if="formShow"></XForm>
      </template>
      <template #toolbar_btns>
        <div class="w-[100%]">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="基础库存表" name="1"></el-tab-pane>
            <el-tab-pane label="差异单据表" name="2"></el-tab-pane>
          </el-tabs>
          <div class="w-[100%] flex gap-x-3 mt-[6px]">
            <div class="flex-1">
              <el-button @click="importHandleClick">
                <span class="flex items-center"> <svg-icon icon-class="import" /> 导出 </span>
              </el-button>
              <!-- <el-button icon="Upload" type="primary" @click="importHandleClick">导出</el-button> -->
            </div>

            <FieldSelectBtn :fieldSelectConfig="fieldSelectConfig" @submit="query" />
          </div>
        </div>
      </template>
      <!-- 在途数量 -->
      <template #InTransit="{ row, column }">
        <VText
          :value="row?.[column.field]"
          :type="Number(row?.[column.field]) ? 'link' : ''"
          @click="Number(row?.[column.field]) && purchaseRouteRef?.open(row, originOption.DocumentTypeEnum['在途'])"
        />
      </template>

      <!-- 锁定库存 -->
      <template #LockedInventory="{ row, column }">
        <VText
          :value="row?.[column.field]"
          :type="Number(row?.[column.field]) ? 'link' : ''"
          @click="Number(row?.[column.field]) && purchaseRouteRef?.open(row, originOption.DocumentTypeEnum['锁库'])"
        />
      </template>

      <!-- 可用库存 -->
      <template #UsableInventory="{ row, column }">
        <VText
          :value="row?.[column.field]"
          :type="Number(row?.[column.field]) ? 'link' : ''"
          @click="Number(row?.[column.field]) && purchaseRouteRef?.open(row, originOption.DocumentTypeEnum['可用'])"
        />
      </template>
    </VTable>
    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>

    <!-- 采购在途 -->
    <purchaseRoute ref="purchaseRouteRef" />
  </VPage>
</template>

<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus"
import XForm from "@/components/XForm/index.vue"
const formShow = ref(false)
import { onMounted, ref, toRefs } from "vue"
import { basicInventoryList, basicInventoryDiffDocumentList } from "@/api/salesInventory"

// 采购在途
import purchaseRoute from "./components/purchaseRoute/index.vue"
const purchaseRouteRef = ref()

const tableRef = ref()
import FieldSelectBtn from "@/views/salesInventory/components/FieldSelectBtn.vue"

// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const importHandleClick = async (e) => {
  let condition = {}
  DerivedCenterRef.value.open({
    tag_name: "performance_indicators",
    condition,
  })
}

const activeName = ref("1")
const handleClick = () => {
  formShow.value = false
  tableRef?.value.resetForm()
  nextTick(() => {
    formShow.value = true
    initTable()
    tableRef?.value?.$table.reloadData([])
    query()
  })
}

// 查询
const query = () => {
  tableRef?.value.query()
}
//获取下拉数据
import { getEnum, getAloneEnum } from "@/utils/enumUtils"
// 枚举 数据
const originOption = ref({})
onMounted(async () => {
  let oneKeys = ["amazonSite", "wmsAttribute", "warehouse"]
  let optData = await getAloneEnum(oneKeys)
  oneKeys.forEach((key) => {
    originOption.value[key] = optData?.[key]
  })
  originOption.value.amazonSite = originOption.value.amazonSite.map((v) => ({ ...v, value: v.label }))

  const DocumentTypeEnum = (await getEnum(["SalesInventoryReport.SirDiffDocuments.DocumentTypeEnum"]))?.["SalesInventoryReport.SirDiffDocuments.DocumentTypeEnum"]

  originOption.value.DocumentTypeEnum = Object.fromEntries(DocumentTypeEnum.map((v) => [v.label, v.value]))
  console.log(originOption.value)
  initTable()
  setTimeout(() => {
    formShow.value = true
  }, 100)
})

const formOption = ref({ inline: true })
const publicStyle = { style: { width: "200px" } }
const fieldList = ref([
  {
    field: "warehouse_id",
    type: "select",
    originField: "warehouse",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "仓库" },
    ...publicStyle,
  },
  {
    field: "warehouse_attr",
    type: "select",
    originField: "wmsAttribute",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "仓库属性" },
    show: (m) => activeName.value == 1,
    ...publicStyle,
  },
  {
    field: "category",
    type: "cascaderNew",
    cascaderType: "category",
    placeholder: "产品品类",
    show: (m) => activeName.value == 1,
    ...publicStyle,
  },
  {
    field: "owner_id",
    type: "cascaderNew",
    placeholder: "货主",
    show: (m) => activeName.value == 1,
    ...publicStyle,
  },
  {
    field: "department_id",
    type: "cascaderNew",
    cascaderType: "department",
    placeholder: "组织维度",
    cascaderProps: {},
    show: (m) => activeName.value == 1,
    ...publicStyle,
  },
  {
    field: "country",
    type: "select",
    originField: "amazonSite",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "国家" },
    show: (m) => activeName.value == 1,
    ...publicStyle,
  },
  {
    field: "order_number",
    placeholder: "单号",
    type: "textarea",
    show: (m) => activeName.value == 2,
    ...publicStyle,
  },
  {
    field: "sku",
    placeholder: "SKU",
    type: "textarea",
    ...publicStyle,
  },

  {
    field: "deadline_at",
    type: "dateTimeRangeNorm",
    itemProps: {
      type: "daterange",
      valueFormat: "YYYY-MM-DD",
    },
    style: { width: "300px" },
  },
])
// 初始化时间
import { parseTime } from "@/utils/ruoyi"
const initDate = () => {
  const temp = new Date()
  temp.setTime(temp.getTime() - 3600 * 1000 * 24 * 30)
  return [new Date(temp.setHours(0, 0, 0, 0)), new Date(new Date().setHours(23, 59, 59, 0))].map((d) => parseTime(d, "{y}-{m}-{d}"))
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: { deadline_at: initDate() },
  },
  columnConfig: {
    resizable: true,
  },
  pagerConfig: undefined,
  rowConfig: { height: 60 },
  border: "outer",
  columns: [],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = {
          page: page.pageNum,
          page_size: page.pageSize,
          ...initForm(form),
        }
        return queryList(params)
      },
    },
  },
})
// 基础库存表
const inventoryColumns = reactive([
  { field: "department_name", title: "一级组织", width: 250 },
  { field: "category_text", title: "一级品类", width: 210 },
  { field: "country", title: "国家", width: 100 },
  { field: "warehouse_name", title: "仓库", width: 100 },
  { field: "owner_name", title: "货主", width: 100 },
  { field: "asin", title: "ASIN", width: 100 },
  { field: "seller_sku", title: "渠道SKU", width: 100 },
  { field: "sku", title: "SKU", width: 100 },
  { field: "type", title: "LT x", width: 100 },
  {
    field: "type",
    title: "平均销量 x",
    width: 100,
    slots: {
      default: ({ row }) => <VText value={row.type} type="link" />,
    },
  },
  { field: "weighted_cost", title: "采购价加权", width: 100 },
  { field: "fba_weighted_cost", title: "头程运费加权", width: 110 },
  // { field: "warehouse_name", title: "仓库", width: 100 },
  {
    title: "在途数量",
    align: "center",
    children: [
      { title: "采购在途", field: "procurement_in_transit", width: 100, slots: { default: "InTransit" } },
      { title: "FBA在途", field: "fba_in_transit", width: 100, slots: { default: "InTransit" } },
      { title: "海外仓在途", field: "ow_in_transit", width: 100, slots: { default: "InTransit" } },
      { title: "海外中转仓在途", field: "otw_in_transit", width: 130, slots: { default: "InTransit" } },
      { title: "WFS在途", field: "wfs_in_transit", width: 100, slots: { default: "InTransit" } },
      { title: "汇总 x", field: "value2", width: 100, slots: { default: "InTransit" } },
    ],
  },
  {
    title: "锁定库存",
    align: "center",
    children: [
      { title: "本地仓锁库 x", field: "value2", width: 100, slots: { default: "LockedInventory" } },
      { title: "FBA锁库1", field: "fba_locked_inventory", width: 100, slots: { default: "LockedInventory" } },
      { title: "海外仓锁库", field: "ow_locked_inventory", width: 100, slots: { default: "LockedInventory" } },
      { title: "海外中转仓锁库", field: "otw_locked_inventory", width: 130, slots: { default: "LockedInventory" } },
      { title: "WFS锁定", field: "wfs_locked_inventory", width: 100, slots: { default: "LockedInventory" } },
      { title: "汇总", field: "locked_inventory_summary", width: 100, slots: { default: "LockedInventory" } },
    ],
  },
  {
    title: "可用库存",
    align: "center",
    children: [
      { title: "本地仓在库 x", field: "value2", width: 100, slots: { default: "UsableInventory" } },
      { title: "FBA在库", field: "fba_available_inventory", width: 100, slots: { default: "UsableInventory" } },
      { title: "海外仓在库", field: "ow_available_inventory", width: 100, slots: { default: "UsableInventory" } },
      { title: "海外中转仓在库", field: "otw_available_inventory", width: 130, slots: { default: "UsableInventory" } },
      { title: "WFS在库", field: "wfs_available_inventory", width: 100, slots: { default: "UsableInventory" } },
      { title: "汇总", field: "available_inventory_summary", width: 100, slots: { default: "UsableInventory" } },
    ],
  },
  {
    title: "金额",
    align: "center",
    children: [
      { title: "采购在途", field: "procurement_in_transit_amount", width: 100 },
      { title: "FBA在途", field: "fba_in_transit_amount", width: 100 },
      { title: "海外仓在途", field: "ow_in_transit_amount", width: 100 },
      { title: "海外中转仓在途", field: "otw_in_transit_amount", width: 130 },
      { title: "WFS在途", field: "wfs_in_transit_amount", width: 100 },

      { title: "本地仓锁库", field: "local_locked_amount", width: 100 },
      { title: "FBA锁库", field: "fba_locked_amount", width: 100 },
      { title: "海外仓锁库", field: "ow_locked_amount", width: 100 },
      { title: "海外中转仓锁库", field: "otw_locked_amount", width: 130 },
      { title: "WFS锁定", field: "wfs_locked_amount", width: 100 },

      { title: "本地仓在库", field: "local_warehouse_inventory_amount", width: 100 },
      { title: "FBA在库", field: "fba_inventory_amount", width: 100 },
      { title: "海外仓在库", field: "ow_inventory_amount", width: 100 },
      { title: "海外中转仓在库", field: "value2", width: 130 },
      { title: "WFS在库", field: "otw_inventory_amount", width: 100 },
      { title: "全流程", field: "wfs_inventory_amount", width: 100 },
    ],
  },
])
// 差异单据列表
const differenceColumns = reactive([
  { type: "checkbox", fixed: "left", width: 60 },
  { type: "seq", title: "序号", width: 60 },
  { field: "order_number", title: "单号", minWidth: 200 },
  { field: "order_status", title: "状态", minWidth: 100 },
  { field: "document_type", title: "类型", minWidth: 100 },
  { field: "sku", title: "SKU", minWidth: 100 },
  { field: "owner_name", title: "货主", minWidth: 100 },
  { field: "quantity", title: "数量", minWidth: 100 },
  { field: "diff_quantity", title: "差异数量", minWidth: 100 },
])
import { filterColumns } from "@/views/salesInventory/components/method.js"
const totalKey = ref("")

const queryList = async (params) => {
  let requests = null
  if (activeName.value == 1) {
    requests = basicInventoryList
  } else {
    requests = basicInventoryDiffDocumentList
  }
  console.log(params)
  return requests(params)
}

const fieldSelectConfig = ref({
  save: "pmcInventory",
  columnsShow: [],
  columns: [],
})
// 组装查询条件
const initForm = (form) => {
  let keys = ["sku", "order_number"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v.trim())
    form[key] = form[key]?.map((v) => v.trim())
  })
  if (form.deadline_at) {
    form.deadline_at = {
      start: form.deadline_at[0],
      end: form.deadline_at[1],
    }
  }
  form.by = activeName.value
  return form
}

const initTable = () => {
  console.log(tableRef?.value)
  let columnsData = []
  if (activeName.value == 1) {
    columnsData = [...inventoryColumns]
  }
  if (activeName.value == 2) {
    columnsData = [...differenceColumns]
  }
  fieldSelectConfig.value.columns = columnsData
  const { columns, key } = filterColumns(columnsData, fieldSelectConfig.value.columnsShow)
  totalKey.value = key
  tableRef?.value?.$table.loadColumn(columns)
  tableRef?.value.updateScroll()
}
</script>
<style lang="scss" scoped>
:deep(.vxe-header--row:nth-child(2)) {
  .vxe-header--column {
    // background: #eff3fe !important;
    background: var(--base-table-hover-bg-color);
  }
}

:deep(.vx-table__content) {
  height: 100%;
  .vxe-grid {
    height: 100%;
  }
}
// :deep(.vxe-body--column) {
//   border-left: 1px solid #e6e7e9;
//   border-bottom: 1px solid #e6e7e9;
// }
// :deep(.vxe-header--column) {
//   border-left: 1px solid #e6e7e9;
//   border-bottom: 1px solid #e6e7e9;
// }
// :deep(.vxe-footer--column) {
//   border-left: 1px solid #e6e7e9;
//   border-bottom: 1px solid #e6e7e9;
// }
:deep(.vxe-body--column) {
  border-left: 1px solid var(--base-link-color);
  border-bottom: 1px solid var(--base-link-color);
}
:deep(.vxe-header--column) {
  border-left: 1px solid var(--base-link-color);
  border-bottom: 1px solid var(--base-link-color);
}
:deep(.vxe-footer--column) {
  border-left: 1px solid var(--base-border-color);
  border-bottom: 1px solid var(--base-border-color);
}

:deep(.vxe-grid) {
  // border-color: red!important;
}
// :deep(.v-page) {
//   background: red;
//   :deep(.v-page__body) {
//     background: pink;
//   }
//   .v-page__body {
//     background: red;
//   }
// }
// :deep(.v-page) {
//   background: pink;

// }

:deep(.vx-table__form-content) {
  background-image: none;
}
.table-view {
  // background: #efefef;
  background: var(--base-color);
  :deep(.vx-table__form) {
  }
  :deep(.vx-table__content) {
    margin-top: 8px;
    // background: #fff;
    background: var(--base-color);
    border-radius: 6px;
    .vxe-buttons--wrapper {
      margin-right: -0.75rem;
    }
  }
  :deep(.vxe-footer--row) {
    // background: #eff3fe;
    background: var(--base-table-hover-bg-color);
  }
}
</style>
